package org.duang.render;

import java.io.IOException;
import java.io.PrintWriter;

import org.duang.config.Config;
import org.duang.kit.ToolsKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

public class JsonRender extends Render {

	private static Logger logger = LoggerFactory.getLogger(JsonRender.class);
	private static final String contentType = "application/json;charset=" + Config.getEncoding();
//	private static final String defaultContentType = "text/plain;charset=" + Config.ENCODING;
	
	public static Render init(){
		return new JsonRender(null);
	}
	
	public JsonRender(Object obj){
		this.obj = obj;
	}
	
	@Override
	public void render() {
		PrintWriter writer = null;
		try {
			response.setHeader("Pragma", "no-cache");	
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			response.setContentType(contentType);
			response.setCharacterEncoding(Config.getEncoding());
			writer = response.getWriter();
//			logger.debug("returnJSON: " + JSON.toJSONStringWithDateFormat(obj, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteDateUseDateFormat));
//	        writer.write(JSON.toJSONStringWithDateFormat(obj, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteDateUseDateFormat));
			writer.write(ToolsKit.toJsonString(obj));
	        writer.flush();
		} catch (IOException e) {
			logger.debug("returnJson exception:  "+e.getMessage(), e);
			throw new IllegalArgumentException(e);
		}
		finally {
			if (writer != null){
				writer.close();
			}
		}
	}

}
